package cn.com.aiton.common.utils;

import cn.com.aiton.common.model.ServiceResult;
import cn.com.aiton.common.model.gbt209992007.GbtCollisionDomain;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

public class JsonToGreenConflictListUtil {

    private static final Logger LOG =
            LoggerFactory.getLogger(JsonToGreenConflictListUtil.class);

    public static ServiceResult phaseCollisionList(String json){
        ServiceResult map = new ServiceResult();
        try {
            JSONArray array = new JSONArray(json);
            List<GbtCollisionDomain> list = new ArrayList<>();
            for(int i=0;i<array.length();i++){
                JSONObject object = array.getJSONObject(i);
                GbtCollisionDomain command = new GbtCollisionDomain();
                command.setPhaseNumber(object.getInt("phaseId"));
                command.setFlag(listToInt(objectToList(object.getJSONArray("collisionPhases"))));
                command.setCollisionPhases(objectToList(object.getJSONArray("collisionPhases")));
                list.add(command);
            }
            map.setSuccess(true);
            map.setObject(list);
            return map;
        }catch (Exception e){
            LOG.error(e.getMessage(),e);
            map.setSuccess(false);
            map.setMessage("数据转换出错");
            return map;
        }
    }

    private static int listToInt(List<Integer> list){
        int i = 0;
        for(int j:list){
            i = i | (1<<(j-1));
        }
        return i;
    }

    private static List<Integer> objectToList(JSONArray array) throws JSONException {
        List<Integer> list = new ArrayList<>();
        for(int i=0;i<array.length();i++){
            list.add(array.getInt(i));
        }
        return list;
    }

}
